package com.yiguantong.police.ui.utils;

/**
 * Created by Administrator on 2016-7-13.
 */

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.ViewConfiguration;

import com.MainApplication;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;

public class PhoneMessage {
    private static String platform = "android";
    private static String imsi = null;
    private static String imei = null;
    private static String phoneModel = null;
    private static String phoneVersion = null;
    private static String screenSize = null;
    private static String WifiMac = "";
    private static String ipV4 = "";
    private static final String marshmallowMacAddress = "02:00:00:00:00:00";
    private static final String fileAddressMac = "/sys/class/net/wlan0/address";

    private static String ip;

    public PhoneMessage() {
    }

    public static String getPlatform() {
        if (platform == null) {
            platform = "android";
        }

        return platform;
    }

    /**
     * 设置网络获取的ip地址
     * @param ipAdd
     */
    public static void setNetworkIpAddress(String ipAdd)
    {
        if (TextUtils.isEmpty(ipAdd)) {
            ip = "";
        }else {
            ip = ipAdd;
        }
    }

    /**
     * 获取缓存的网络ip地址
     * @return
     */
    public static String getNetworkIpAddress()
    {
        if (TextUtils.isEmpty(ip))
            return "";
        return ip;
    }

    //获取ip地址
    public static String getIPV4Address() {
        if (!TextUtils.isEmpty(ipV4))
            return ipV4;
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress();
                        //boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                        boolean isIPv4 = sAddr.indexOf(':') < 0;
                        if (isIPv4)
                            return sAddr;
                    }
                }
            }
        } catch (Exception ex) {
        } // for now eat exceptions
        return "";
    }

    /**
     * 校验是否被二次签名
     *
     * @param context
     * @return
     */
    public static long getSignature(Context context) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi;
        StringBuilder sb = new StringBuilder();

        try {
            pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            Signature[] signatures = pi.signatures;
            for (Signature signature : signatures) {
                sb.append(signature.toCharsString());
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return sb.toString().hashCode();
    }

    /**
     * 是不是模拟器运行
     *
     * @return
     */
    private static String TAG = "henry";

    public static boolean isEmulator() {
     /*   String s = "FINGERPRINT=" + Build.FINGERPRINT + "\nMODEL=" + Build.MODEL
                + "\nMANUFACTURER=" + Build.MANUFACTURER + "\nBRAND=" + Build.BRAND + "\n" + "Build.DEVICE=" + Build.DEVICE
                + "\nBuild.PRODUCT=" + Build.PRODUCT + "\nBuild.HARDWARE=" + Build.HARDWARE;
                */
//        Log.d("henry", s);


     /*  s =  "Build.ID:"+Build.ID
        +"\nBuild.DISPLAY:"+Build.DISPLAY
       +"\nBuild.PRODUCT:"+Build.PRODUCT
       +"\nBuild.DEVICE:"+Build.DEVICE
       +"\nBuild.BOARD:"+Build.BOARD
       +"\nBuild.MANUFACTURER:"+Build.MANUFACTURER
       +"\nBuild.BRAND:"+Build.BRAND
       +"\nBuild.MODEL:"+Build.MODEL
       +"\nBuild.BOOTLOADER:"+Build.BOOTLOADER
       +"\nBuild.HARDWARE:"+Build.HARDWARE
       +"\nBuild.SERIAL:"+Build.SERIAL
        //Log.i(TAG, "Build.SUPPORTED_ABIS:"+Build.SUPPORTED_ABIS);
        //Log.i(TAG, "Build.SUPPORTED_32_BIT_ABIS:"+Build.SUPPORTED_32_BIT_ABIS);
        //Log.i(TAG, "Build.SUPPORTED_64_BIT_ABIS:"+Build.SUPPORTED_64_BIT_ABIS);
       +"\nBuild.VERSION.INCREMENTAL:"+Build.VERSION.INCREMENTAL
       +"\nBuild.VERSION.RELEASE:"+Build.VERSION.RELEASE
       +"\nBuild.VERSION.SDK:"+Build.VERSION.SDK
       +"\nBuild.VERSION.SDK_INT:"+Build.VERSION.SDK_INT
       +"\nBuild.VERSION.CODENAME:"+Build.VERSION.CODENAME
       +"\nBuild.TYPE:"+Build.TYPE
       +"\nBuild.TAGS:"+Build.TAGS
       +"\nBuild.FINGERPRINT:"+Build.FINGERPRINT
       +"\nBuild.TIME:"+Build.TIME
       +"\nBuild.USER:"+Build.USER
       +"\nBuild.HOST:"+Build.HOST;



        Toast.makeText(MainApplication.getIns(), s, Toast.LENGTH_LONG).show();*/
      /* String s = "FINGERPRINT=" + Build.FINGERPRINT + "\nMODEL=" + Build.MODEL
                + "\nMANUFACTURER=" + Build.MANUFACTURER + "\nBRAND=" + Build.BRAND + "\n" + "Build.DEVICE=" + Build.DEVICE
                + "\nBuild.PRODUCT=" + Build.PRODUCT + "\nBuild.HARDWARE=" + Build.HARDWARE;
//        Log.d("henry", s);

       +"Build.ID:"+Build.ID);
       +"Build.DISPLAY:"+Build.DISPLAY);
       +"Build.PRODUCT:"+Build.PRODUCT);
       +"Build.DEVICE:"+Build.DEVICE);
       +"Build.BOARD:"+Build.BOARD);
       +"Build.MANUFACTURER:"+Build.MANUFACTURER);
       +"Build.BRAND:"+Build.BRAND);
       +"Build.MODEL:"+Build.MODEL);
       +"Build.BOOTLOADER:"+Build.BOOTLOADER);
       +"Build.HARDWARE:"+Build.HARDWARE);
       +"Build.SERIAL:"+Build.SERIAL);
        //Log.i(TAG, "Build.SUPPORTED_ABIS:"+Build.SUPPORTED_ABIS);
        //Log.i(TAG, "Build.SUPPORTED_32_BIT_ABIS:"+Build.SUPPORTED_32_BIT_ABIS);
        //Log.i(TAG, "Build.SUPPORTED_64_BIT_ABIS:"+Build.SUPPORTED_64_BIT_ABIS);
       +"Build.VERSION.INCREMENTAL:"+Build.VERSION.INCREMENTAL);
       +"Build.VERSION.RELEASE:"+Build.VERSION.RELEASE);
       +"Build.VERSION.SDK:"+Build.VERSION.SDK);
       +"Build.VERSION.SDK_INT:"+Build.VERSION.SDK_INT);
       +"Build.VERSION.CODENAME:"+Build.VERSION.CODENAME);
       +"Build.TYPE:"+Build.TYPE);
       +"Build.TAGS:"+Build.TAGS);
       +"Build.FINGERPRINT:"+Build.FINGERPRINT);
       +"Build.TIME:"+Build.TIME);
       +"Build.USER:"+Build.USER);
       +"Build.HOST:"+Build.HOST);
        //Log.i(TAG, "Build.IS_DEBUGGABLE:"+Build.IS_DEBUGGABLE);*/
       /* MainApplication.getIns().tip("FINGERPRINT=" + Build.FINGERPRINT + "\nMODEL=" + Build.MODEL
                + "\nMANUFACTURER=" + Build.MANUFACTURER + "\nBRAND=" + Build.BRAND + "\n");*/
        return /*Build.FINGERPRINT.startsWith("generic")
                || Build.FINGERPRINT.startsWith("unknown")*/

                Build.FINGERPRINT.contains("test-keys")
                        || Build.FINGERPRINT.startsWith("Android")
                        || Build.MODEL.contains("google_sdk")
                        || Build.MODEL.contains("Emulator")
                        || Build.MODEL.contains("Android SDK built for x86")
                        || Build.MODEL.contains("Android SDK built for x86_64")
                        || Build.MANUFACTURER.contains("Genymotion")
                        || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
                        || "google_sdk".equals(Build.PRODUCT);
    }

    /**
     * 网络识别
     */
    public static String getNetworkInfo(Context context) {
        String netWorkModel = null;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null && info.isAvailable() && info.isConnected() && info.getState() == State.CONNECTED) {
            if (info.getTypeName().equals("WIFI")) {
                netWorkModel = "WIFI";
            } else {
                TelephonyManager telmng = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                if (telmng.getDataState() == 2) {
                    System.out.println("net work type: " + telmng.getNetworkType());
                    switch (telmng.getNetworkType()) {
                        case 0:
                            netWorkModel = "unknown";
                            break;
                        case 1:
                            netWorkModel = "gprs";
                            System.out.println("gprs");
                            break;
                        case 2:
                            System.out.println("edge");
                            netWorkModel = "edge";
                            break;
                        case 3:
                            System.out.println("umts");
                            netWorkModel = "umts";
                            break;
                        case 4:
                            System.out.println("cdma");
                            netWorkModel = "cdma";
                            break;
                        case 5:
                        case 6:
                            System.out.println("evdo");
                            netWorkModel = "evdo";
                            break;
                        case 7:
                        case 9:
                        default:
                            netWorkModel = "unknown";
                            break;
                        case 8:
                            System.out.println("hsdpa");
                            netWorkModel = "hsdpa";
                            break;
                        case 10:
                            System.out.println("hspa");
                            netWorkModel = "hspa";
                    }
                }
            }
        }

        return netWorkModel;
    }

    /**
     * 手机系统版本
     */
    public static String getPhoneVersion() {
        if (phoneVersion == null) {
            phoneVersion = VERSION.RELEASE;
        }

        return phoneVersion;
    }

    /**
     * 手机型号
     */
    public static String getPhoneModel() {
        if (phoneModel == null) {
            phoneModel = Build.MODEL;
        }

        return phoneModel;
    }


    /**
     * IMSI号
     */
    public static String getIMSI(Context context) {
//        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//        if (imsi == null) {
//            imsi = tm.getSubscriberId();
//        }
//
//        return imsi;
        String applicationIMSI = MainApplication.IMSI;
        if (applicationIMSI == null || applicationIMSI.equals(""))
            return getDeviceId();
        return applicationIMSI;
    }

    /**
     * IMEI号
     */
    public static String getIMEI(Context context) {
        String applicationIMEI = MainApplication.IMEI;
        if (applicationIMEI == null || applicationIMEI.equals(""))
            return getDeviceId();
        return applicationIMEI;
    }

    /**
     * ANDROID_ID
     */
    public static String getANDROID_ID(Context context) {
        String androidId = "";
        androidId = SharedPreferencesUtil.getInfoString(MainApplication.getIns(),"ANDROID_ID","");
        if(TextUtils.isEmpty(androidId)) {
            androidId = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            SharedPreferencesUtil.putInfoString(MainApplication.getIns(), "ANDROID_ID", androidId);
        }
        return androidId;
    }

    public static String getSign(String channel, String packageName, String appKey, String pwd, String cstamp) {
        return MD5Util.MD5(getPlatform() + channel + packageName + appKey + pwd + cstamp);
    }

    public static String getSign(String signContent, String pwd, String cstamp) {
        return MD5Util.MD5(getPlatform() + signContent + pwd + cstamp);
    }

    /**
     * 可变的UUID
     */
    public static String getRandomUUID() {
        UUID uuid = UUID.randomUUID();
        String uniqueId = uuid.toString();
        return uniqueId.replaceAll("-", "");
    }


    /**
     * 视频模块生成设备识别码
     *
     * @return
     */
    public static String getVideoDeviceId() {
        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        String applicationIMEI = MainApplication.IMEI;
        if (TextUtils.isEmpty(applicationIMEI)) {
            return new UUID(m_szDevIDShort.hashCode(), applicationIMEI.hashCode()).toString();
        }
        String serial;
        try {
            serial = android.os.Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            serial = "serial"; // 需要一个初始化值
        }
        //使用硬件信息拼凑出来的15位号码(不需要任何设备权限，替换原有需要设备权限的方法)
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }


    /**
     * DeviceId
     */
    public static String getDeviceId() {
        String serial = null;
        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            serial = android.os.Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            serial = "serial"; // 需要一个初始化值
        }
        //使用硬件信息拼凑出来的15位号码(不需要任何设备权限，替换原有需要设备权限的方法)
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();

    }

    /**
     * 品牌
     *
     * @return 品牌
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 是否是需要的厂商
     */
    public static boolean isFactoryMatching(String factory) {
        if (TextUtils.isEmpty(factory))
            return false;
        String facturer = android.os.Build.MANUFACTURER;
        String brand = Build.BRAND;
        if (!TextUtils.isEmpty(facturer) && facturer.toLowerCase().contains(factory.toLowerCase()))
            return true;
        if (!TextUtils.isEmpty(brand) && brand.toLowerCase().contains(factory.toLowerCase()))
            return true;
        return false;
    }

    //是否是华为手机
    public static boolean isMatchingHuawei() {
        return isFactoryMatching("huawei");
    }

    //是否小米设备(MiUi都认为小米设备,小米推送依赖Miui)
    public static boolean isMatchingXiaoMi() {
        if (isFactoryMatching("xiaomi"))
            return true;
        try {
            final BuildProperties prop = BuildProperties.newInstance();
            return prop.getProperty("ro.miui.ui.version.code", null) != null || prop.getProperty("ro.miui.ui.version.name", null) != null
                    || prop.getProperty("ro.miui.internal.storage", null) != null;
        } catch (final IOException e) {
            return false;
        }
    }
    //    是否是OPPO手机
    public static boolean isMatchingOppo(){
        return isFactoryMatching("oppo");
    }

    //是否是vivo手机
    public static boolean isMatchingViVo() {
        return isFactoryMatching("vivo");
    }

    public static class BuildProperties {
        private final Properties properties;

        private BuildProperties() {
            properties = new Properties();
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(new File(Environment.getRootDirectory(), "build.prop"));
                properties.load(fis);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public boolean containsKey(final Object key) {
            return properties.containsKey(key);
        }

        public boolean containsValue(final Object value) {
            return properties.containsValue(value);
        }

        public Set<Map.Entry<Object, Object>> entrySet() {
            return properties.entrySet();
        }

        public String getProperty(final String name) {
            return properties.getProperty(name);
        }

        public String getProperty(final String name, final String defaultValue) {
            return properties.getProperty(name, defaultValue);
        }

        public boolean isEmpty() {
            return properties.isEmpty();
        }

        public Enumeration<Object> keys() {
            return properties.keys();
        }

        public Set<Object> keySet() {
            return properties.keySet();
        }

        public int size() {
            return properties.size();
        }

        public Collection<Object> values() {
            return properties.values();
        }

        public static BuildProperties newInstance() throws IOException {
            return new BuildProperties();
        }
    }

    //是否具有通知权限 0:拒绝 1：允许 2：无法获取
    public static int getNotificationEnabledState(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
            return 2;
        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            if ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED)
                return 1;
            return 0;

        } catch (Exception e) {
            e.printStackTrace();
            return 2;
        }
    }

    //获得屏幕方向
    public static int getScreenOrientation(Activity activity) {
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        int orientation;
        // if the device's natural orientation is portrait:
        if ((rotation == Surface.ROTATION_0
                || rotation == Surface.ROTATION_180) && height > width ||
                (rotation == Surface.ROTATION_90
                        || rotation == Surface.ROTATION_270) && width > height) {
            switch (rotation) {
                case Surface.ROTATION_0:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                    break;
                case Surface.ROTATION_90:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                    break;
                case Surface.ROTATION_180:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                    break;
                case Surface.ROTATION_270:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                    break;
                default:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                    break;
            }
        }
        // if the device's natural orientation is landscape or if the device
        // is square:
        else {
            switch (rotation) {
                case Surface.ROTATION_0:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                    break;
                case Surface.ROTATION_90:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                    break;
                case Surface.ROTATION_180:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                    break;
                case Surface.ROTATION_270:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                    break;
                default:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                    break;
            }
        }

        return orientation;
    }

    /**
     * Desc: 获取虚拟按键高度 放到工具类里面直接调用即可
     */
    public static int getNavigationBarHeight(Context context) {
        int result = 0;
        if (hasNavBar(context)) {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId);
            }
        }
        MyLog.i("虚拟键盘高度"+result);
        return result;
    }

    /**
     * 获取状态栏高度
     */
    public static int getStatusBarHeight(Context context)
    {
        if (context==null)
            return 0;
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 检查是否存在虚拟按键栏
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            // check override flag
            String sNavBarOverride = getNavBarOverride();
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else { // fallback
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
    }

    /**
     * 判断虚拟按键栏是否重写
     *
     * @return
     */
    private static String getNavBarOverride() {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable e) {
            }
        }
        return sNavBarOverride;
    }
}